<?php

namespace App\Services;

use App\Repository\Contracts\MenuRepository;
use App\Traits\TreeFormat;
use Illuminate\Support\Collection;

class MenuService
{
    use TreeFormat;

    /**
     * @var MenuRepositoryEloquent
     */
    protected $menuRepository;

    public function __construct(MenuRepository $menuRepository)
    {
        $this->menuRepository = $menuRepository;
    }

   /**
    * Get Menus  and paginate.
    *
    * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
    */
    public function getMenus()
    {
        $menuList = $this->menuRepository->getAllMenuList();

        return $this->treeSortMultiLevelFormat($menuList->toArray());
    }

   /**
    * Get one Menu  by primary key.
    *
    * @param $id
    * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
    */
    public function getMenu($id)
    {
        return $this->menuRepository->find($id);
    }

   /**
    * Create a new line on Menu.
    *
    * @param array $data
    * @return \Illuminate\Database\Eloquent\Model|$this
    */
    public function storeMenu($data)
    {
        return $this->menuRepository->create($data);
    }

   /**
    * Update Menu one line by primary key.
    *
    * @param $id
    * @param array $data
    * @return int
    */
    public function updateMenu($id, $data)
    {
        return $this->menuRepository->update($id, $data);
    }

   /**
    * Delete Menu one line by primary key.
    *
    * @param $id
    * @return mixed
    */
    public function deleteMenu($id)
    {
        return $this->menuRepository->deleteById($id);
    }

    /**
     * 菜单根据权限显示，并格式化
     *
     * @param Collection $permission
     * @return array
     */
    public function getMenuListByPermission(Collection $permission): array
    {
        $menuList = $this->menuRepository->getAllMenuList();
        $filtered = $menuList->filter(function ($value) use ($permission) {
            return $permission->contains('name', $value->slug);
        })->toArray();

        return $this->treeSortMultiLevelFormat($filtered);
    }

}